package Presentacion.ArticulosStock.AjusteDeStock;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.JTextField;

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;

import java.awt.Checkbox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JTabbedPane;

import java.awt.FlowLayout;
import java.util.List;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;

import Logica.ArticulosStock.ABMArticulosLogica;
import Logica.ArticulosStock.ABMDepositoLogica;
import Logica.ArticulosStock.ABMRubrosLogica;
import Modelo.Articulo;
import Modelo.Deposito;
import Modelo.Rubros;
import Presentacion.ArticulosStock.ABMArticulos.BuscarArticulos;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class AjustesDeStock extends JFrame {

	private JPanel contentPane, panelConsultaStock, panelAjusteStock;
	private JTextField tfCodigo;
	private JTextField tfDescripcionCorta;
	private JTextField tfStockActual;
	private JTextField tfDescripcionLarga;
	private JTextField tfCantidad;
	private JTextField tfStockAjustado;
	private JTable tablaRubros;
	private JTable table;
	private JTabbedPane tabbedPrincipal;
	private JScrollPane scTablaFamilia, scrollPane;
	private JButton btnStockPorDeposito, btnImprimeFaltantes, btnLimpiarControlStock, btnGuardar, btnLimpiarAjusteStock, btnImprimir,
					btnBuscar;
	private JComboBox cbDeposito, cbTipoMovimiento;
	private DefaultTableModel model, modelRubros;

	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AjustesDeStock frame = new AjustesDeStock();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public AjustesDeStock() {
		setResizable(false);
		setTitle("Ajustes de stock");
		this.setVisible(true);
//		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		/**Pregunto si al presionar la "X" esta seguro de que quiere cerrar la ventana.*/
		this.addWindowListener(new WindowAdapter() {
	           public void windowClosing(WindowEvent e) {
	        	   setDefaultCloseOperation(0); 
	        	   cerrarVentana();
	           }
	       });		
		setBounds(100, 100, 870, 407);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(192, 192, 192));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		tabbedPrincipal = new JTabbedPane(JTabbedPane.TOP);
		tabbedPrincipal.setBounds(0, 0, 854, 379);
		contentPane.add(tabbedPrincipal);
		
		panelConsultaStock = new JPanel();
		tabbedPrincipal.addTab("Consulta de Stock", null, panelConsultaStock, null);
		panelConsultaStock.setLayout(null);
		
		scTablaFamilia = new JScrollPane();
		scTablaFamilia.setBounds(10, 10, 170, 208);
		panelConsultaStock.add(scTablaFamilia);
		
		tablaRubros = new JTable();
		tablaRubros.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2){
					// Aqui hacemos algo 
					try {
						dobleClickRubros();
					} catch (Exception e2) {
						e2.printStackTrace();						
					}
				}					
			}
		});
		tablaRubros.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                	dobleClickRubros();
                }
            }
		});
		scTablaFamilia.setViewportView(tablaRubros);
		this.initTablaFamilia();

		btnStockPorDeposito = new JButton("Stock por dep\u00F3sito");
		btnStockPorDeposito.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			}
		});
		btnStockPorDeposito.setBounds(10, 224, 170, 25);
		panelConsultaStock.add(btnStockPorDeposito);
		
		btnImprimeFaltantes = new JButton("Imprime FALTANTES");
		btnImprimeFaltantes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			}
		});
		btnImprimeFaltantes.setBounds(10, 253, 170, 25);
		panelConsultaStock.add(btnImprimeFaltantes);
		
		scrollPane = new JScrollPane();
		scrollPane.setBounds(190, 10, 649, 330);
		panelConsultaStock.add(scrollPane);
		
		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2){
					try {
						dobleClickArticulos();
					} catch (Exception e2) {
						e2.printStackTrace();						
					}
				}					
			}
		});
		table.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                	dobleClickArticulos();
                }
            }
		});
		scrollPane.setViewportView(table);
		this.initTabla("");

		btnLimpiarControlStock = new JButton("");
		btnLimpiarControlStock.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
			}
		});
		btnLimpiarControlStock.setIcon(new ImageIcon(AjustesDeStock.class.getResource("/Presentacion/Img/limpiar.png")));
		btnLimpiarControlStock.setToolTipText("Limpiar");
		btnLimpiarControlStock.setBounds(60, 282, 65, 65);
		panelConsultaStock.add(btnLimpiarControlStock);
		
		panelAjusteStock = new JPanel();
		tabbedPrincipal.addTab("Ajustes de Stock", null, panelAjusteStock, null);
		panelAjusteStock.setLayout(null);
		
		JLabel lblDeposito = new JLabel("Deposito:");
		lblDeposito.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblDeposito.setBounds(10, 10, 70, 15);
		panelAjusteStock.add(lblDeposito);
		
		cbDeposito = new JComboBox();
		cbDeposito.setBounds(80, 8, 178, 20);
		panelAjusteStock.add(cbDeposito);
		
		JSeparator separator1 = new JSeparator();
		separator1.setBounds(80, 35, 560, 2);
		panelAjusteStock.add(separator1);
		
		JSeparator separator2 = new JSeparator();
		separator2.setBounds(80, 263, 560, 2);
		panelAjusteStock.add(separator2);
		
		JSeparator separator3 = new JSeparator();
		separator3.setOrientation(SwingConstants.VERTICAL);
		separator3.setBounds(80, 35, 3, 230);
		panelAjusteStock.add(separator3);
		
		JSeparator separator4 = new JSeparator();
		separator4.setOrientation(SwingConstants.VERTICAL);
		separator4.setBounds(640, 35, 3, 230);
		panelAjusteStock.add(separator4);
		
		btnGuardar = new JButton("");
		btnGuardar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			}
		});
		btnGuardar.setToolTipText("Guardar");
		btnGuardar.setIcon(new ImageIcon(AjustesDeStock.class.getResource("/Presentacion/Img/guardar.png")));
		btnGuardar.setBounds(565, 172, 65, 65);
		panelAjusteStock.add(btnGuardar);
		
		btnLimpiarAjusteStock = new JButton("");
		btnLimpiarAjusteStock.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				limpiar();
			}
		});
		btnLimpiarAjusteStock.setToolTipText("Limpiar");
		btnLimpiarAjusteStock.setIcon(new ImageIcon(AjustesDeStock.class.getResource("/Presentacion/Img/limpiar.png")));
		btnLimpiarAjusteStock.setBounds(565, 96, 65, 65);
		panelAjusteStock.add(btnLimpiarAjusteStock);
		
		JLabel lblCodigo = new JLabel("C\u00F3digo:");
		lblCodigo.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblCodigo.setBounds(90, 54, 70, 15);
		panelAjusteStock.add(lblCodigo);
		
		tfCodigo = new JTextField();
		tfCodigo.addFocusListener(new FocusAdapter() {			
			public void focusGained(FocusEvent arg0) {
				pintaVerde(tfCodigo);
			}			
			public void focusLost(FocusEvent arg0) {
				pintaBlanco(tfCodigo);
			}
		});
		tfCodigo.setBounds(145, 48, 140, 20);
		panelAjusteStock.add(tfCodigo);
		tfCodigo.setColumns(10);
		tfCodigo.requestFocus();
		
		btnImprimir = new JButton("");
		btnImprimir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			}
		});
		btnImprimir.setIcon(new ImageIcon(AjustesDeStock.class.getResource("/Presentacion/Img/impresora.png")));
		btnImprimir.setBounds(332, 48, 30, 30);
		panelAjusteStock.add(btnImprimir);
		
		btnBuscar = new JButton("");
		btnBuscar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				buscar();
			}
		});
		btnBuscar.setIcon(new ImageIcon(AjustesDeStock.class.getResource("/Presentacion/Img/lupita.png")));
		btnBuscar.setBounds(292, 48, 30, 30);
		panelAjusteStock.add(btnBuscar);
		
		tfDescripcionCorta = new JTextField();
		tfDescripcionCorta.setEditable(false);
		tfDescripcionCorta.setBounds(93, 86, 364, 20);
		panelAjusteStock.add(tfDescripcionCorta);
		tfDescripcionCorta.setColumns(10);
		
		JLabel lblStockActual = new JLabel("Stock Actual:");
		lblStockActual.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblStockActual.setBounds(93, 117, 107, 14);
		panelAjusteStock.add(lblStockActual);
		
		tfStockActual = new JTextField();
		tfStockActual.setEditable(false);
		tfStockActual.setBounds(188, 110, 97, 25);
		panelAjusteStock.add(tfStockActual);
		tfStockActual.setColumns(10);
		
		JLabel lblDescripcion = new JLabel("Descripci\u00F3n:");
		lblDescripcion.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblDescripcion.setBounds(90, 150, 80, 15);
		panelAjusteStock.add(lblDescripcion);
		
		tfDescripcionLarga = new JTextField();
		tfDescripcionLarga.addFocusListener(new FocusAdapter() {			
			public void focusGained(FocusEvent arg0) {
				pintaVerde(tfDescripcionLarga);
			}			
			public void focusLost(FocusEvent arg0) {
				pintaBlanco(tfDescripcionLarga);
			}
		});
		tfDescripcionLarga.setBounds(90, 168, 449, 20);
		panelAjusteStock.add(tfDescripcionLarga);
		tfDescripcionLarga.setColumns(10);
		
		JLabel lblTipoMovimiento = new JLabel("Tipo movimiento:");
		lblTipoMovimiento.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblTipoMovimiento.setBounds(90, 196, 120, 15);
		panelAjusteStock.add(lblTipoMovimiento);
		
		cbTipoMovimiento = new JComboBox();
		cbTipoMovimiento.setBounds(201, 194, 178, 20);
		panelAjusteStock.add(cbTipoMovimiento);
		
		JLabel lblCantidad = new JLabel("Cantidad:");
		lblCantidad.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblCantidad.setBounds(93, 222, 120, 15);
		panelAjusteStock.add(lblCantidad);
		
		tfCantidad = new JTextField();
		tfCantidad.addFocusListener(new FocusAdapter() {			
			public void focusGained(FocusEvent arg0) {
				pintaVerde(tfCantidad);
			}			
			public void focusLost(FocusEvent arg0) {
				pintaBlanco(tfCantidad);
			}
		});
		tfCantidad.setBounds(159, 220, 86, 20);
		panelAjusteStock.add(tfCantidad);
		tfCantidad.setColumns(10);
		
		JLabel lblStockAjustado = new JLabel("Stock Ajustado:");
		lblStockAjustado.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblStockAjustado.setBounds(255, 225, 107, 14);
		panelAjusteStock.add(lblStockAjustado);
		
		tfStockAjustado = new JTextField();
		tfStockAjustado.setEditable(false);
		tfStockAjustado.setColumns(10);
		tfStockAjustado.setBounds(371, 218, 97, 25);
		panelAjusteStock.add(tfStockAjustado);
		
		JSeparator separator = new JSeparator();
		separator.setOrientation(SwingConstants.VERTICAL);
		separator.setBounds(556, 35, 3, 230);
		panelAjusteStock.add(separator);
		
		this.initDeposito();
	}
	
	/*Metodo para confirma si esta seguro que quiere cerrar la aplicacinn*/	
	public void cerrarVentana(){
					this.setVisible(false);	
	}
	
	public void initTablaFamilia(){
		modelRubros = new DefaultTableModel(
				new Object[][] {
					{null},
					{null},
					{null},
					{null},
					{null},
					{null},
					{null},
					{null},
					{null},
					{null},
					{null},
					{null},
				},
				new String[] {
					""
				}
			) {
				Class[] columnTypes = new Class[] {
					String.class
				};
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
				boolean[] columnEditables = new boolean[] {
					false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			};
		tablaRubros.setModel(modelRubros);
		
		this.cargaRubros();		
	}
	
	public void cargaRubros(){		
		
		List<Rubros>list = ABMRubrosLogica.getList();
		if (list.size() > 0){
			modelRubros.setRowCount(0);
			for (Rubros x : list) {
				modelRubros.addRow(new Object[] { 					  
						 x.getNombre()					 				 
						 });
				 }
		}				
	}
	
	public void initTabla(String rubro){
		model = new DefaultTableModel(
				new Object[][] {
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					{null, null, null, null, null, null},
					
					
				},
				new String[] {
					"Codigo", "Detalle", "S.Minimo", "S.Actual", "Leyenda", "Ult.Proveedor"
				}
			) {
				Class[] columnTypes = new Class[] {
					String.class, String.class, String.class, String.class, String.class, String.class
				};
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
				boolean[] columnEditables = new boolean[] {
					false, false, false, false, false, false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			};
			table.setModel(model);
			
			table.getColumnModel().getColumn(0).setPreferredWidth(60);
			table.getColumnModel().getColumn(0).setMinWidth(40);
			table.getColumnModel().getColumn(1).setPreferredWidth(150);
			table.getColumnModel().getColumn(1).setMinWidth(100);
			table.getColumnModel().getColumn(2).setPreferredWidth(70);
			table.getColumnModel().getColumn(2).setMinWidth(30);
			table.getColumnModel().getColumn(3).setPreferredWidth(70);
			table.getColumnModel().getColumn(3).setMinWidth(30);
			table.getColumnModel().getColumn(4).setPreferredWidth(70);
			table.getColumnModel().getColumn(4).setMinWidth(30);
			table.getColumnModel().getColumn(5).setPreferredWidth(100);
			table.getColumnModel().getColumn(5).setMinWidth(40);
			
			
			if (!rubro.equals("")){
				List<Articulo>listA = ABMArticulosLogica.getListByRubro(rubro);
				model.setRowCount(0);
				for (Articulo x : listA) {
					model.addRow(new Object[] { 
							x.getId(),
							x.getNombre(),
							x.getStockMin(),
							x.getStockea(),
							x.getStockMax(),
							x.getUltimoProveedor()
							 });
					 }
			}
	}
	
	public void dobleClickRubros(){
		int seleccion = tablaRubros.getSelectedRow();
		if (seleccion != -1) {
			String str;
			str = (String) tablaRubros.getValueAt(seleccion, 0);
			try {
				this.initTabla(str);
			} catch (Exception e) {
				e.printStackTrace();
			}			
			}
		else{
			JFrame frame = new JFrame();
            JOptionPane.showMessageDialog(frame, 
            		"*  Debe seleccionar un item", "Error", 
            		JOptionPane.WARNING_MESSAGE);
			}		
	}
	
	public void dobleClickArticulos(){
		int seleccion = table.getSelectedRow();
		if (seleccion != -1) {
			try {
			Integer cod;
			System.out.println("elemento: "+model.getValueAt(4, 0));
			cod =  (Integer) model.getValueAt(seleccion, 0);
			
				this.ajustaStock(cod);
			} catch (Exception e) {
				e.printStackTrace();
			}			
			}
		else{
			JFrame frame = new JFrame();
            JOptionPane.showMessageDialog(frame, 
            		"*  Debe seleccionar un item", "Error", 
            		JOptionPane.WARNING_MESSAGE);
			}
	}
	
	public void ajustaStock(Integer cod){
		if(!cod.equals("")){
			Articulo a = ABMArticulosLogica.getById(cod);
			tfCodigo.setText(Integer.toString(a.getId()));
			tfDescripcionCorta.setText(a.getNombre());
			tfStockActual.setText(Integer.toString(a.getStockea()));
			tfStockAjustado.setText(Integer.toString(a.getStockMin()));
			
			/** pasa del panel "Control de Stock" al panel "Ajustes de Stock"*/
			tabbedPrincipal.setSelectedIndex(tabbedPrincipal.indexOfComponent(panelAjusteStock));
		}
	}
	
	public void limpiar(){
		tfCodigo.setText("");
		tfDescripcionCorta.setText("");
		tfStockActual.setText("");
		tfStockAjustado.setText("");
		tfCantidad.setText("");
		tfDescripcionLarga.setText("");		
	}
	
    public void initDeposito(){
        List<Deposito>list = null;
        list = ABMDepositoLogica.getList();
        cbDeposito.addItem("");  
        for(int i = 0; i <list.size(); i++) {
                String a = list.get(i).getNombre();
                cbDeposito.addItem(a); 
           } 
        }
    
    
//  ** Pinto JTEXTFIELD de color   **  // 
  public void pintaVerde(JTextField tf){
		tf.setBackground(new Color(153, 255, 153));
	}	
	public void pintaBlanco(JTextField tf){
		tf.setBackground(new Color(255, 255, 255));
	}
	
	public void buscar(){
		new BuscarArticulos(this);
	}
	
}
